package com.example.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.Mapper.UsersMapper;
import com.example.Objects.AuthenticationRequest;
import com.example.Objects.AuthenticationResponse;
import com.example.Objects.PO.Users;
import com.example.Objects.RegisterRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@RequiredArgsConstructor
@ComponentScan("com.example.config.ApplicationConfig")
public class AuthenticationService {

    private final PasswordEncoder passwordEncoder;
    private final JwtService jwtService;
    private final UsersMapper repository;
    private final AuthenticationManager authenticationManager;


    public AuthenticationResponse register(RegisterRequest request) {
        //这里密码需要加密 但因为password是int的缘故暂且等下
        Users users = new Users(request.getMail(),passwordEncoder.encode(request.getPassword()));
        repository.insert(users);
        var jwtToken = jwtService.generateToken(users);

        return AuthenticationResponse.builder()
                .accessToken(jwtToken)
                .build();
    }

    public AuthenticationResponse authenticate(AuthenticationRequest request) {
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getMail(), request.getPassword()));
        //更改后的代码
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("email",request.getMail());
        wrapper.eq("password",request.getPassword());

        List<Users> userList=repository.selectList(wrapper);
        //需要写一个根据名字搜索的service逻辑
//        var user = repository.selectById(1);
        var jwtToken = jwtService.generateToken(userList.get(0));

        return AuthenticationResponse.builder()
                .accessToken(jwtToken)
                .build();
    }
}
